package at.newmedialab.sn.services.geo;

import at.newmedialab.sn.exceptions.GeoCodingFailedException;
import org.geonames.FeatureClass;
import org.geonames.Toponym;
import org.geonames.ToponymSearchCriteria;
import org.geonames.ToponymSearchResult;

import javax.enterprise.context.ApplicationScoped;
import java.util.List;

/**
 * User: Thomas Kurz
 * Date: 13.04.11
 * Time: 09:01
 */
@ApplicationScoped
public class GeoServiceImpl {

	public Toponym getToponym(String address) throws GeoCodingFailedException {
		return getToponyms(address).get(0);
	}

	public Toponym getToponym(String address, String nearby) throws GeoCodingFailedException {
		return getToponyms(address, nearby).get(0);
	}

	public List<Toponym> getToponyms(String address) throws GeoCodingFailedException {
		return getToponyms(address, null);
	}

	public List<Toponym> getToponyms(String address, String nearby) throws GeoCodingFailedException {
		final ToponymSearchCriteria searchCriteria = new ToponymSearchCriteria();
        searchCriteria.setQ(address);
		searchCriteria.setMaxRows(1);
        searchCriteria.setFeatureClass(FeatureClass.P); // only look for cities and places
        try {
        	final ToponymSearchResult searchResult = org.geonames.WebService.search(searchCriteria);
        	if (searchResult.getTotalResultsCount() == 0) {
        		throw new GeoCodingFailedException("no results for "+address);
			}
        	return searchResult.getToponyms();
        } catch (final Exception e) {
        	throw new GeoCodingFailedException(e);
        }
	}

}
